package com.roam.service;

import com.roam.entity.EmailOnly;
import com.roam.entity.RegisterMail;
import com.roam.entity.User;
import com.roam.jwt.Jwt;
import com.roam.result.Result;
import com.roam.utils.ValidateCodeUtils;
import jakarta.annotation.Resource;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;




@Service
public class SendMessageService {
    @Value("${spring.mail.username}")
    private String from;
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserService userService;


    //该服务用于向目标邮箱发送验证码并保存在redis中
    public Result sendMessage(EmailOnly emailOnly){
        String email =emailOnly.getEmail();
        System.out.println(email);
        String redisKey = String.format("my:user:sendMessage:%s",email);
        ValueOperations<String,Object>valueOperations=redisTemplate.opsForValue();
        //防刷验证
        try{
            RegisterMail preMsg= (RegisterMail)valueOperations.get(redisKey);
            String preCode = preMsg.getCode();
            if(!StringUtil.isEmpty(preCode)){
                Long ttl = redisTemplate.getExpire(redisKey,TimeUnit.MINUTES);
                System.out.println(ttl);
                if(ttl>=4){
                    return Result.success("一分钟内无法对同一邮箱发送信息");
                }
            }
        }catch (Exception e){

        }
        //设置邮件发送所需信息
        String subject="RoamTouring系统";
        String code = ValidateCodeUtils.generateValidateCode().toString();
        String text ="【RoamTouring系统】您好，您的验证码为："+code+",请在五分钟内使用，若非本人操作，可以忽视本条信息。";
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email);
        message.setSubject(subject);
        message.setText(text);
        //发送邮件
        try {
            javaMailSender.send(message);
        }catch (Exception e){
            System.out.println("邮件发送失败");
            return Result.error("邮件发送失败");
        }
        //将验证码存入redis
        RegisterMail registerMail1=new RegisterMail();
        registerMail1.setEmail(email);
        registerMail1.setCode(code);


        try{
            valueOperations.set(redisKey,registerMail1,5, TimeUnit.MINUTES);
            RegisterMail preserveMsg =(RegisterMail) valueOperations.get(redisKey);
            System.out.println(preserveMsg);
            return Result.success("验证码发送成功");
        }catch (Exception e){
            System.out.println("存入redis失败");
            e.printStackTrace();
            return Result.error("未知错误");
        }
    }
   /*
   该方法用于检查验证码正确性
   */
    public Result checkCode(RegisterMail registerMail){
        String email=registerMail.getEmail();
        String code = registerMail.getCode();
        String redisKey = String.format("my:user:sendMessage:%s",email);
        ValueOperations<String,Object> valueOperations =redisTemplate.opsForValue();
        RegisterMail preserveMsg =(RegisterMail) valueOperations.get(redisKey);
        System.out.println(preserveMsg);
        if(!Optional.ofNullable(preserveMsg).isPresent()){
            System.out.println("验证码不存在");
            return  Result.error("验证码不存在");
        }else{
            String preserveCode = preserveMsg.getCode();
            if(!code.equals(preserveCode)){
                System.out.println("验证码错误");
                return Result.error("邮箱或验证码错误");
            }else{
                User user = userService.getInfoByEmail(email);
                if(user!=null){
                    int userId = user.getUserID();
                    Map<String,Object>claims = new HashMap<>();
                    claims.put("email",email);
                    String jwt = Jwt.generateJwt(claims);
                    Map<String,Object> data = new HashMap<>();
                    data.put("userID",userId);
                    data.put("token",jwt);
                    Result result = new Result<>(1,"登录成功",data);
                    return result;
                }else{
                   if(userService.saveRegisterInfo(email)){
                       User user1 = userService.getInfoByEmail(email);
                       int useId = user1.getUserID();
                       Map<String,Object>claims = new HashMap<>();
                       claims.put("email",email);
                       String jwt = Jwt.generateJwt(claims);
                       Map<String,Object> data = new HashMap<>();
                       data.put("userID",useId);
                       data.put("token",jwt);
                       Result result = new Result(1,"注册成功",data);
                       return result;
                   }else {
                       System.out.println("未知错误");
                       return Result.error("未知错误");
                   }
                }
            }
        }
    }
}
